<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Web高级开发 | Advanced Web Development Course</title>
    <link rel="stylesheet" href="../../css/main.css" />
    <link rel="stylesheet" href="../../css/tabs.css" />
    <script src="../../js/uikit.js"></script>
    <link href="../../css/prism.css" rel="stylesheet" />
    <script src="../../js/prism.js"></script>
  </head>

  <body>
    <div
      data-uk-sticky="animation: uk-animation-slide-top; sel-target: .uk-navbar-container; cls-active: uk-navbar-sticky; cls-inactive: uk-navbar-transparent; top: 300"
    >
      <nav class="uk-navbar-container pt-2 pb-2">
        <div class="uk-container">
          <div data-uk-navbar>
            <div class="uk-navbar-left">
              <a
                class="uk-navbar-item uk-logo uk-visible@m"
                href="../../index.html"
                >Web高级开发课程</a
              >
              <a
                class="uk-navbar-tuk-containeroggle uk-hidden@m"
                href="#offcanvas-docs"
                data-uk-toggle
                ><span data-uk-navbar-toggle-icon></span>
                <span class="uk-margin-small-left">目录</span></a
              >
              <ul class="uk-navbar-nav uk-visible@m">
                <li><a href="../../index.html">文档</a></li>
              </ul>
            </div>
            <div class="uk-navbar-center uk-hidden@m">
              <a class="uk-navbar-item uk-logo" href="../../index.html"
                >Web高级开发课程</a
              >
            </div>
          </div>
        </div>
      </nav>
    </div>

    <div class="uk-section">
      <div class="uk-container">
        <div class="uk-grid-large" data-uk-grid>
          <div class="sidebar-fixed-width uk-visible@m">
            <div class="sidebar-docs uk-position-fixed uk-margin-top">
              <h5>关于这门课</h5>
              <ul class="uk-nav uk-nav-default doc-nav">
                <li><a href="../../index.html">大纲</a></li>
              </ul>
              <h5>章节</h5>
              <ul class="uk-nav uk-nav-default doc-nav">
                <li><a href="../01.html">第1章 - Spring基础</a></li>
                <li><a href="../02.html">第2章 - Spring中的Bean</a></li>
                <li><a href="../03.html">第3章 - Spring AOP</a></li>
                <li><a href="../04.html">第4章 - Spring的事物管理</a></li>
                <li><a href="../05.html">第5章 - 初识MyBatis</a></li>
                <li><a href="../06.html">第6章 - MyBatis的核心配置</a></li>
                <li><a href="../07.html">第7章 - MyBatis的高级应用</a></li>
                <li><a href="../08.html">第8章 - Spring MVC入门</a></li>
                <li><a href="../09.html">第9章 - Spring MVC数据绑定</a></li>
                <li><a href="../10.html">第10章 - Spring MVC拦截器</a></li>
                <li><a href="../11.html">第11章 - Spring Boot基础</a></li>
                <li><a href="../12.html">第12章 - Spring Boot的Web开发</a></li>
                <li>
                  <a href="../13.html">第13章 - Spring Boot的数据库连接</a>
                </li>
                <li><a href="../14.html">第14章 - 框架整合</a></li>
              </ul>
              <h5>实验课</h5>
              <ul class="uk-nav uk-nav-default doc-nav">
                <li><a href="./code-01.html">01</a></li>
                <li><a href="./code-02.html">02</a></li>
                <li><a href="./code-03.html">03</a></li>
                <li><a href="./code-04.html">04</a></li>
                <li><a href="./code-05.html">05</a></li>
                <li><a href="./code-06.html">06</a></li>
                <li class="uk-active"><a href="./code-07.html">07</a></li>
                <li><a href="./code-08.html">08</a></li>
                <li><a href="./code-09.html">09</a></li>
                <li><a href="./code-10.html">10</a></li>
                <li><a href="./code-11.html">11</a></li>
                <li><a href="./code-12.html">12</a></li>
              </ul>
            </div>
          </div>
          <div class="uk-width-1-1 uk-width-expand@m">
            <article class="uk-article">
              <h1>实验课07 - 数据绑定，注解</h1>
<div>

  <h4>2. 对依赖（注入）数据的封装</h4>
<p>在controller里加入</p>
<pre><code class='language-java' lang='java'>@RequestMapping(path=&quot;/account&quot;, method = {RequestMethod.POST})
public String show(Account account){
    System.out.println(account);
    return &quot;success&quot;;
}
</code></pre>
<p>在index.jsp中加入表单的代码</p>
<pre><code class='language-xml' lang='xml'>&lt;form action=&quot;account&quot; method=&quot;post&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;money&quot; placeholder=&quot;资金&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;user.username&quot; placeholder=&quot;用户名&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;user.password&quot; placeholder=&quot;密码&quot;&gt;
    &lt;input type=&quot;submit&quot; value=&quot;提交&quot;&gt;
&lt;/form&gt;
</code></pre>
<h4>3.解决中文乱码的问题</h4>
<p>在web.xml中配置Spring提供的过滤器</p>
<pre><code class='language-xml' lang='xml'>  &lt;!-- 配置过滤器，解决中文乱码问题 --&gt;
  &lt;filter&gt;
    &lt;filter-name&gt;characterEncodingFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt;
    &lt;init-param&gt;
      &lt;param-name&gt;encoding&lt;/param-name&gt;
      &lt;param-value&gt;UTF-8&lt;/param-value&gt;
    &lt;/init-param&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
    &lt;filter-name&gt;characterEncodingFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
</code></pre>
<h4>4. 自定义类型转换器</h4>
<p>新建一个package utils，在里面定义StringToDateConverter.java类</p>
<pre><code class='language-java' lang='java'>package com.qust.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateConverter implements Converter&lt;String, Date&gt; {
    @Override
    public Date convert(String source) {
        if(source == null) {
            throw new RuntimeException(&quot;参数不能为空&quot;);
        }
        try {
            DateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;);
            Date date = df.parse(source);
            return date;
        } catch (Exception e) {
            throw new RuntimeException(&quot;类型转换错误&quot;);
        }
    }
}

</code></pre>
<p>在springmvc.xml配置文件中加入：</p>
<pre><code class='language-xml' lang='xml'>&lt;bean id=&quot;conversionService&quot;
          class=&quot;org.springframework.context.support.ConversionServiceFactoryBean&quot;&gt;
    &lt;property name=&quot;converters&quot;&gt;
        &lt;set&gt;
            &lt;bean class=&quot;com.qust.utils.StringToDateConverter&quot;/&gt;
        &lt;/set&gt;
    &lt;/property&gt;
&lt;/bean&gt;
</code></pre>
<p>并且在</p>
<pre><code class='language-xml' lang='xml'>&lt;mvc:annotation-driven&gt;
</code></pre>
<p>中加入conversion-service=&quot;conversionService&quot;变成下面这样</p>
<pre><code class='language-xml' lang='xml'>&lt;mvc:annotation-driven conversion-service=&quot;conversionService&quot;/&gt;
</code></pre>
<h4>5. 常用注解</h4>
<p>@RequestParam</p>
<p>在controller中加入</p>
<pre><code class='language-java' lang='java'>@RequestMapping(path=&quot;testRequestParam&quot;)
public String testRequestParam(@RequestParam(value=&quot;username&quot;, required=false)String name){
    System.out.println(&quot;testRequestParam...&quot;);
    System.out.println(name);
    return &quot;success&quot;;
}
</code></pre>
<p>注意这个时候前端部分就要用username了，而不能用name去传值</p>
<p>比如这样是可以的：</p>
<pre><code class='language-html' lang='html'>&lt;a href=&quot;testRequestParam?username=abc&quot;&gt;testRequestParam&lt;/a&gt;
</code></pre>
<p>而这样是不可以的</p>
<pre><code class='language-java' lang='java'>&lt;a href=&quot;testRequestParam?name=abc&quot;&gt;testRequestParam&lt;/a&gt;
</code></pre>
<p>也不是说不可以，只不过最后打印name的时候，会显示null</p>
<p>&nbsp;</p>
<p>@RequestBody</p>
<p>在controller中加入</p>
<pre><code class='language-java' lang='java'>@RequestMapping(path=&quot;testRequestBody&quot;)
public String testRequestBody(@RequestBody String body){
    System.out.println(&quot;testRequestBody...&quot;);
    System.out.println(body);
    return &quot;success&quot;;
}
</code></pre>
<p>在前端jsp文件中加入</p>
<pre><code class='language-html' lang='html'>&lt;form action=&quot;testRequestBody&quot; method=&quot;post&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;名字&quot;&gt;
    &lt;input type=&quot;submit&quot; value=&quot;提交&quot;&gt;
&lt;/form&gt;
</code></pre>
<p>在填入username后点击提交，后台就会打印出请求体的内容，内容如下</p>
<pre><code>username=你输入的名字
</code></pre>
<p>&nbsp;</p>
<p>@pathVariable</p>
<p>在controller中加入</p>
<pre><code class='language-java' lang='java'>@RequestMapping(path=&quot;pathVariable/{id}&quot;)
public String pathVariable(@PathVariable(value=&quot;id&quot;) String id){
    System.out.println(&quot;testPathVariable...&quot;);
    System.out.println(id);
    return &quot;success&quot;;
}
</code></pre>
<p>在前端jsp文件中加入</p>
<pre><code class='language-html' lang='html'>&lt;a href=&quot;pathVariable/998&quot;&gt;pathVariable-998&lt;/a&gt;
</code></pre>
<p>运行后，后台就可以打印出998了</p>
<img src="../../images/lab07/restful.png" alt="restful">
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>@RequestHeader  (用的比较少)</p>
<p>在controller中加入</p>
<pre><code class='language-java' lang='java'>@RequestMapping(path=&quot;requestHeader&quot;)
public String requestHeader(@RequestHeader(value=&quot;Accept&quot;) String header){
    System.out.println(header);
    return &quot;success&quot;;
}
</code></pre>
<p>在前端jsp文件中加入</p>
<pre><code class='language-html' lang='html'>&lt;a href=&quot;requestHeader&quot;&gt;test requestHeader&lt;/a&gt;
</code></pre>
<p>运行后，后台就可以打印出header的信息了：比如text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,<em>/</em>;q=0.8,application/signed-exchange;v=b3;q=0.9 ...</p>
<p>&nbsp;</p>
<p>@CookieValue</p>
<p>在controller中加入</p>
<pre><code class='language-java' lang='java'>@RequestMapping(path=&quot;cookieValue&quot;)
public String testCookieValue(@CookieValue(value=&quot;JSESSIONID&quot;) String cookieValue){
    System.out.println(&quot;testCookieValue... &quot;);
    System.out.println(cookieValue);
    return &quot;success&quot;;
}
</code></pre>
<p>在前端jsp文件中加入</p>
<pre><code class='language-html' lang='html'>&lt;a href=&quot;cookieValue&quot;&gt;cookieValue&lt;/a&gt;
</code></pre>
<img src="../../images/lab07/session.png" alt="session">
<p>&nbsp;</p>
<p>@ModelAttribute</p>
<p>带返回值的方式:</p>
<p>在controller中加入</p>
<pre><code class='language-java' lang='java'>@ModelAttribute
public User showUser(String name){
    System.out.println(&quot;showUser执行了&quot;);
	// 模拟从数据库中取数据
    User user = new User();
    user.setUsername(name);
    user.setPassword(&quot;111&quot;);

    return user;
}


@RequestMapping(path=&quot;testModelAttribute&quot;)
public String testModelAttribute(User user){
    System.out.println(&quot;testModelAttribute... &quot;);
    System.out.println(user);
    return &quot;success&quot;;
}
</code></pre>
<p>在前端jsp文件中加入</p>
<pre><code class='language-html' lang='html'>&lt;form action=&quot;testModelAttribute&quot; method=&quot;post&quot;&gt;
    &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;名字&quot;&gt;
    &lt;input type=&quot;submit&quot; value=&quot;提交&quot;&gt;
&lt;/form&gt;
</code></pre>
<p>运行后就会打印出用户名和密码</p>
<p>注意这里在提交的时候，没有输入密码</p>
<p>或者还有一种，没有返回值的方式是加个了map</p>
<p>在controller中加入</p>
<pre><code class='language-java' lang='java'>@ModelAttribute
public void showUser(String name, Map&lt;String, User&gt; map) {
    System.out.println(&quot;showUser执行了&quot;);

    User user = new User();
    user.setUsername(name);
    user.setPassword(&quot;111&quot;);

    map.put(&quot;yonghu&quot;, user);
}


@RequestMapping(path=&quot;testModelAttribute&quot;)
public String testModelAttribute(@ModelAttribute(value=&quot;yonghu&quot;) User user){
    System.out.println(&quot;testModelAttribute... &quot;);
    System.out.println(user);
    return &quot;success&quot;;
}
</code></pre>
<p>前端不变</p>
<p>运行后依然会打印出用户名和密码</p>
<p>@SessionAttributes</p>
<p>用于多次执行控制器方法间的参数共享</p>
<p>在controller这个类的最上面添加</p>
<pre><code class='language-java' lang='java'>@SessionAttributes(value={&quot;username&quot;,&quot;password&quot;}, types={String.class, Integer.class})
</code></pre>
<p>然后加入下面的方法：</p>
<pre><code class='language-java' lang='java'>@RequestMapping(path=&quot;saveSession&quot;)
public String saveSession(Model model){
    System.out.println(&quot;向session中保存数据&quot;);
    model.addAttribute(&quot;username&quot;, &quot;root&quot;);
    model.addAttribute(&quot;password&quot;, &quot;123&quot;);

    return &quot;success&quot;;
}


@RequestMapping(path=&quot;getSession&quot;)
public String getSession(ModelMap modelMap){
    String username = (String) modelMap.get(&quot;username&quot;);
    String password = (String) modelMap.get(&quot;password&quot;);
    System.out.println(username + &quot; &quot; + password);
    return &quot;success&quot;;
}

@RequestMapping(path=&quot;deleteSession&quot;)
public String deleteSession(SessionStatus status){
    status.setComplete();
    return &quot;success&quot;;
}
</code></pre>
<p>前端加入</p>
<pre><code class='language-html' lang='html'>&lt;a href=&quot;saveSession&quot;&gt;saveSession&lt;/a&gt;
&lt;a href=&quot;getSession&quot;&gt;getSession&lt;/a&gt;
&lt;a href=&quot;deleteSession&quot;&gt;deleteSession&lt;/a&gt;
</code></pre>
<p>当发起这三种不同的请求的时候，就可以对session进行不同的操作。</p>


</div>
            </article>
          </div>
        </div>
      </div>
    </div>




    <div id="offcanvas-docs" data-uk-offcanvas="overlay: true">
      <div class="uk-offcanvas-bar">
        <button class="uk-offcanvas-close" type="button" data-uk-close></button>
        <h5 class="uk-margin-top">关于这门课</h5>
        <ul class="uk-nav uk-nav-default doc-nav">
          <li><a href="../indext.html">大纲</a></li>
        </ul>
        <h5 class="uk-margin-top">章节</h5>
        <ul class="uk-nav uk-nav-default doc-nav">
          <li><a href="../01.html">第1章 - Spring基础</a></li>
          <li><a href="../02.html">第2章 - Spring中的Bean</a></li>
          <li><a href="../03.html">第3章 - Spring AOP</a></li>
          <li><a href="../04.html">第4章 - Spring的事物管理</a></li>
          <li><a href="../05.html">第5章 - 初识MyBatis</a></li>
          <li><a href="../06.html">第6章 - MyBatis的核心配置</a></li>
          <li><a href="../07.html">第7章 - MyBatis的高级应用</a></li>
          <li><a href="../08.html">第8章 - Spring MVC入门</a></li>
          <li><a href="../09.html">第9章 - Spring MVC数据绑定</a></li>
          <li><a href="../10.html">第10章 - Spring MVC拦截器</a></li>
          <li><a href="../11.html">第11章 - Spring Boot基础</a></li>
          <li><a href="../12.html">第12章 - Spring Boot的Web开发</a></li>
          <li><a href="../13.html">第13章 - Spring Boot的数据库连接</a></li>
          <li><a href="../14.html">第14章 - 框架整合</a></li>
        </ul>
        <h5>实验课</h5>
        <ul class="uk-nav uk-nav-default doc-nav">
          <li><a href="./code-01.html">01</a></li>
          <li><a href="./code-02.html">02</a></li>
          <li><a href="./code-03.html">03</a></li>
          <li><a href="./code-04.html">04</a></li>
          <li><a href="./code-05.html">05</a></li>
          <li><a href="./code-06.html">06</a></li>
          <li class="uk-active"><a href="./code-07.html">07</a></li>
          <li><a href="./code-08.html">08</a></li>
          <li><a href="./code-09.html">09</a></li>
          <li><a href="./code-10.html">10</a></li>
          <li><a href="./code-11.html">11</a></li>
          <li><a href="./code-12.html">12</a></li>
        </ul>
      </div>
    </div>

    <footer class="uk-section uk-text-center uk-text-muted">
      <div class="uk-container uk-container-small">
        <div class="uk-margin-medium"></div>
      </div>
    </footer>

    <script src="../js/awesomplete.js"></script>
    <script src="../js/custom.js"></script>
  </body>
</html>
